from hashlib import md5
import random
import json
import time
import sys
import os
try:
    import requests
except:
    os.system("pip3 install requests")
    import requests

def make_md5(s, encoding='utf-8'):
    return md5(s.encode(encoding)).hexdigest()


def translate(text):
    salt = random.randint(32768, 65536)
    sign = make_md5(main.appid + text + str(salt) + main.appkey)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    payload = {'appid': main.appid, 'q': text, 'from': translate.from_lang, 'to': translate.to_lang, 'salt': salt, 'sign': sign}
    r = requests.post(translate.url, params=payload, headers=headers)
    fetch = r.json()['trans_result']
    #v = json.dumps(fetch, indent=4, ensure_ascii=False)
    result = ''
    for i in fetch:
        result = '%s%s\n%s\n\n' %(result, i['src'], i['dst'])

    return result


def main(txtPath, maxlenth = 6000):

    f = open(txtPath, encoding = 'UTF8', mode = 'r')
    f2 = open("%s.%s.txt" %(os.path.basename(txtPath)[:-4], time.time()), encoding='UTF8', mode='a+')
    lines = f.readlines()
    f.close()
    while lines:
        print("\t-----行数剩余%s-----" %len(lines), end='\r')
        v = next((lines[:n] for n in range(len(lines), 0, -1) if len(' '.join(lines[:n])) < maxlenth), lines[:1])
        v2 = ''.join(v)

        if len(v2) > maxlenth:
            print("存在超过%s字的分段，不予翻译" %maxlenth, end='\r')
            f2.write(v2)
            continue
        else:
            f2.write(translate(v2))

        lines = lines[len(v):]

        time.sleep(1)

    print()

if __name__ == '__main__':
    # For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`
    translate.from_lang = 'en'
    translate.to_lang =  'zh'
    translate.url = 'http://api.fanyi.baidu.com/api/trans/vip/translate'

    try:
        main.appid = os.environ['API_APPID_2gy6']
        main.appkey = os.environ['API_APPKEY_2gy6']
    
    except:
        print("You may set API_APPID_2gy6 and API_APPKEY_2gy6")
        print("via https://fanyi-api.baidu.com/manage/developer")
        sys.exit()

    if not len(sys.argv) <2:
        for i in sys.argv[1:]:
            if i[-4:] == '.txt':
                main(i.strip('\'\"\\').rstrip("/"))
    else:
        print("To Split a txt with a certain number of words:")
        print("python *this [*txt.path]")
